<template>
  <div>
    <div class="top">
        <div class="top_left">
          <span class="textA">直流电源</span>/<span class="textB">拓扑展示</span>
        </div>
        <div class="top_right">
          <div class="box_A">A路</div>
          <div class="box_B">B路</div>
        </div>
    </div>
    <div id="scroll-container" style="position: relative;">
      <div class="bottom" ref="stageContainer"></div>
    </div>
  </div>
  

</template>
<script>
  import Konva from 'konva';
  import {getPowerinfor} from "@/api/index"
  export default {
    data() {
      return {
        isDragging: false, // 用于标记是否正在拖动
        lastPointerPos: null, // 记录上一次鼠标指针的位置
        // Alist:{},
        // Blist:{},
        Alist:{id:11,state:"开启",branch:[
          {id: 1, deviceId: "001-1", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          {id: 2, deviceId: "001-2", deviceName: "汇聚分支2", deviceType: "汇聚分支",status:"故障",apower:102,avoltage:"220v",acurrent:"0.2A",},
          {id: 3, deviceId: "001-3", deviceName: "汇聚分支3", deviceType: "汇聚分支",status:"在线",apower:103,avoltage:"220v",acurrent:"0.2A",},
          {id: 4, deviceId: "001-4", deviceName: "汇聚分支4", deviceType: "汇聚分支",status:"在线",apower:104,avoltage:"220v",acurrent:"0.2A",},
          {id: 5, deviceId: "001-5", deviceName: "汇聚分支5", deviceType: "汇聚分支",status:"离线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 1, deviceId: "001-1", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 2, deviceId: "001-2", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"故障",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 3, deviceId: "001-3", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 4, deviceId: "001-4", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 5, deviceId: "001-5", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"离线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 1, deviceId: "001-1", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 2, deviceId: "001-2", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"故障",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 3, deviceId: "001-3", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 4, deviceId: "001-4", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:106,avoltage:"220v",acurrent:"0.2A",},
          // {id: 5, deviceId: "001-5", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"离线",apower:106,avoltage:"220v",acurrent:"0.2A",},
        ]},
        Blist:{id:22,state:"开启",branch:[
          {id: 8, deviceId: "002-1", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          {id: 9, deviceId: "002-2", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          {id: 10, deviceId: "002-3", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          {id: 11, deviceId: "002-4", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          {id: 12, deviceId: "002-5", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 8, deviceId: "002-1", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 9, deviceId: "002-2", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 10, deviceId: "002-3", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 11, deviceId: "002-4", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 12, deviceId: "002-5", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 8, deviceId: "002-1", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 9, deviceId: "002-2", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 10, deviceId: "002-3", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 11, deviceId: "002-4", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
          // {id: 12, deviceId: "002-5", deviceName: "汇聚分支1", deviceType: "汇聚分支",status:"在线",apower:101,avoltage:"220v",acurrent:"0.2A",},
        ]},
        scaleAgroup:0
      }
    },
    mounted(){
      this.initStage();
      this.getData();
    },
    methods:{
      initStage() {
        this.stage = new Konva.Stage({
          container: this.$refs.stageContainer,
          width: window.innerWidth,
          height: window.innerHeight,
        });
        this.stage.draw();
      },
      getData(){
        // getPowerinfor().then(resp => {
        //   this.Alist = resp.data.A;
        //   this.Blist = resp.data.B;
          this.$nextTick(() => {
            this.stage = new Konva.Stage({
              container: this.$refs.stageContainer,
              width: this.$refs.stageContainer.offsetWidth,
              height: this.$refs.stageContainer.offsetHeight,
              draggable: false
            });
            const layer = new Konva.Layer();
              // 创建一个主 Group 来管理所有元素
              const mainGroup = new Konva.Group();
              // 提取创建矩形和文本的函数
              const createRectAndText = (x, y, width, height, fill,textLeft, textRight, name) => {
                const rect = new Konva.Rect({
                  x,
                  y,
                  width,
                  height,
                  fill,
                  stroke: 'black',
                  strokeWidth: 2,
                  name,
                });
                const textLeftObj = new Konva.Text({
                  x: x + 5,
                  y: y + 5,
                  text: textLeft,
                  fontSize: 12,
                  fontFamily: 'Arial',
                  fill: 'black',
                  align: 'left',
                  textAlign: 'left',
                });
                const textRightObj = new Konva.Text({
                  x: x + width - 20,
                  y: y + height - 15,
                  text: textRight,
                  fontSize: 12,
                  fontFamily: 'Arial',
                  fill: 'black',
                  align: 'right',
                  textAlign: 'right',
                });
                //创建斜线
                const line = new Konva.Line({
                  points: [x + width, y, x, y + height],
                  stroke: 'black',
                  strokeWidth: 2,
                });
                layer.add(rect);
                layer.add(textLeftObj);
                layer.add(textRightObj);
                layer.add(line);
                // 创建一个组来管理矩形和文本
                const group = new Konva.Group();
                group.add(rect);
                group.add(textLeftObj);
                group.add(textRightObj);
                group.add(line);
                // 添加点击事件监听器
                rect.on('click', () => {
                  // this.handleDialog(name);
                });
                // return { rect, textObj };
                // layer.add(group);
                mainGroup.add(group);
                return group;
              };
              // 提取创建虚线矩形和文本的函数
              const createDashedRectAndText = (x, y, width, height, text, name) => {
                const rect = new Konva.Rect({
                  x,
                  y,
                  width,
                  height,
                  stroke: 'black',
                  strokeWidth: 2,
                  dash: [5, 3],
                  fill: 'transparent',
                  name,
                  draggable:true
                });
                const textObj = new Konva.Text({
                  x: x + 20,
                  y: y - 20,
                  text,
                  fontSize: 14,
                  fontFamily: 'Arial',
                  fill: 'black',
                  align: 'left'
                });
                // 创建一个组来管理虚线矩形和文本
                const group = new Konva.Group();
                group.add(rect);
                group.add(textObj);
                // layer.add(group);
                mainGroup.add(group);
                return group;
              };
              // 创建箭头函数
              const createArrow = (x, y, length, color, name) => {
                const arrow = new Konva.Arrow({
                  points: [x, y, x, y + length],
                  pointerLength: 10,
                  pointerWidth: 10,
                  fill: color,
                  stroke: color,
                  strokeWidth: 2,
                  name
                });
                // layer.add(arrow);
                return arrow;
              };
              // 创建实心圆函数
              const createCircle = (x, y, radius, fill, name) => {
                const circle = new Konva.Circle({
                  x,
                  y,
                  radius,
                  fill,
                  stroke: 'black',
                  strokeWidth: 2,
                  name
                });
                // layer.add(circle);
                return circle;
              };
              // 创建贯穿线函数
              const createLine = (x1, y1, x2, y2, stroke, strokeWidth, name) => {
                const line = new Konva.Line({
                  points: [x1, y1, x2, y2],
                  stroke,
                  strokeWidth,
                  name
                });
                // layer.add(line);
                return line;
              };
              const xSpacing = 60;
              const yStart = 40;
              const dcScreenCabinetWidth = 300; // 直流屏柜宽度
              const dcPowerCabinetWidth = 180; // 直流配电柜宽度
              const dcPowerCabinetHeight = 150; // 直流配电柜高度
              const dcScreenCabinetHeight = 100; // 直流屏柜高度
              const subComponentWidth = 50; // 子组件宽度
              const subComponentHeight = 35; // 子组件高度
              const subComponentSpacing = 20; // 子组件间隔
              // 进电线的位置和尺寸
              const inletWireWidth = 20;
              const inletWireHeight = 90;
              // let aGroup = null;
              if (this.Alist) {
                // 创建 A 路相关元素的组
                const aGroup = new Konva.Group();
                // 绘制进电线 A 路
                const inletWireCircleA = createCircle(
                  xSpacing / 2,
                  yStart + (dcPowerCabinetHeight - inletWireHeight) / 2,
                  inletWireWidth / 2,
                  'red',
                  'inletWireCircleA'
                );
                aGroup.add(inletWireCircleA);
                const inletWireA = createArrow(
                  xSpacing / 2,
                  yStart + (dcPowerCabinetHeight - inletWireHeight) / 2 + inletWireWidth / 2,
                  inletWireHeight - inletWireWidth,
                  'red',
                  'inletWireA'
                );
                aGroup.add(inletWireA);
                // A路与箭头垂直的线
                const verticalLineA = createLine(
                  xSpacing / 2,
                  yStart + dcPowerCabinetHeight - inletWireHeight / 2,
                  xSpacing / 2 + dcScreenCabinetWidth + dcPowerCabinetWidth * 3,
                  yStart + dcPowerCabinetHeight - inletWireHeight / 2,
                  'red',
                  2,
                  'verticalLineA'
                );
                const cGroup = new Konva.Group();
                // aGroup.add(verticalLineA);
                cGroup.add(verticalLineA)
                // A路总开关
                const imageMainswitch = new Image();
                imageMainswitch.onload = () => {
                  // 图片加载完成后，更新 imagezongkai 变量
                  this.imagezongkai = imageMainswitch;
                  const aMainSwitchImage = new Konva.Image({
                    x: xSpacing + subComponentSpacing,
                    y: yStart+ subComponentSpacing + subComponentHeight+28,
                    image: this.imagezongkai, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'aMainSwitchImage',
                    rotation:-90,
                    // draggable:true
                    scaleX: -1  // 水平翻转
                  });
                  aGroup.add(aMainSwitchImage);
                  // 重新绘制 layer 和 stage
                  layer.draw();
                  this.stage.draw();
                };
                imageMainswitch.src = require("@/assets/openswitch.png");
                //A路AC/DC
                const aRectifierModule = createRectAndText(
                  xSpacing + subComponentSpacing*3 + subComponentWidth,
                  yStart + dcPowerCabinetHeight - dcScreenCabinetHeight + subComponentSpacing*2,
                  subComponentWidth,
                  subComponentHeight,
                  'white',
                  'AC',
                  'DC',
                  'aRectifierModule'
                );
                aGroup.add(aRectifierModule);
                // 获取 aRectifierModule 的位置和尺寸信息
                const aRectifierX = aRectifierModule.children[0].x();
                const aRectifierY = aRectifierModule.children[0].y();
                const aRectifierWidth = aRectifierModule.children[0].width();
                const aRectifierHeight = aRectifierModule.children[0].height();

                // 向下引申的线
                const downLine = createLine(
                  aRectifierX + aRectifierWidth / 2, // 从矩形底部中间开始
                  aRectifierY + aRectifierHeight+5,
                  aRectifierX + aRectifierWidth / 2,
                  aRectifierY + aRectifierHeight + 50, // 向下延伸 50 像素
                  'black',
                  2,
                  'downLineFromRect'
                );
                // 右侧引申的线
                const rightLine = createLine(
                  aRectifierX + aRectifierWidth, // 从矩形右侧中间开始
                  aRectifierY + aRectifierHeight / 2,
                  aRectifierX + aRectifierWidth + 50, // 向右延伸 50 像素
                  aRectifierY + aRectifierHeight / 2,
                  'black',
                  2,
                  'rightLineFromRect'
                );
                // 右侧引申线再向下延伸的线
                const rightDownLine = createLine(
                  aRectifierX + aRectifierWidth + 50, // 从右侧引申线的末端开始
                  aRectifierY + aRectifierHeight / 2,
                  aRectifierX + aRectifierWidth + 50,
                  aRectifierY + aRectifierHeight + 50, // 向下延伸到和向下引申线相同的高度
                  'black',
                  2,
                  'rightDownLineFromRect'
                );
                //引申地线
                const connectLine = createLine(
                  aRectifierX + aRectifierWidth / 2,
                  aRectifierY + aRectifierHeight + 50,
                  aRectifierX + aRectifierWidth + 50,
                  aRectifierY + aRectifierHeight + 50,
                  'black',
                  2,
                  'connectLine'
                );
                const lineMidX = (aRectifierX + aRectifierWidth / 2 + aRectifierX + aRectifierWidth + 50) / 2;
                const lineMidY = aRectifierY + aRectifierHeight + 50;
                const imageOnLine  = new Image();
                imageOnLine.onload = () => {
                  const konvaImage = new Konva.Image({
                    x: lineMidX + 15, // 根据图片大小调整位置
                    y: lineMidY - 10, // 根据图片大小调整位置
                    image: imageOnLine,
                    width: 20, // 图片宽度
                    height: 20, // 图片高度
                    name: 'imageOnLine',
                    rotation:90
                  });
                  aGroup.add(konvaImage);
                  layer.draw();
                };
                imageOnLine.src = require("@/assets/switchclose.png");
                aGroup.add(downLine);
                aGroup.add(rightLine);
                aGroup.add(rightDownLine);
                aGroup.add(connectLine);
                // aGroup.add(imageOnLine);
                // A路汇聚终端
                const imageAterm = new Image();
                imageAterm.onload = () => {
                  // 图片加载完成后，更新 imagezongkai 变量
                  this.imageTerm = imageAterm;
                  const aTerminal = new Konva.Image({
                    x: xSpacing * 3 + dcScreenCabinetWidth +15,
                    y: yStart + subComponentSpacing+subComponentHeight+25,
                    image: this.imageTerm, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'aTerminal',
                    rotation:90,
                    draggable:true
                  });
                  // layer.add(aTerminal);
                  // layer.draw();
                  // this.stage.draw();
                  aGroup.add(aTerminal);
                  layer.draw();
                  this.stage.draw();
                };
                imageAterm.src = require("@/assets/避雷器.png");
                // A路直流输出总开关
                const imageAdcout = new Image();
                imageAdcout.onload = () => {
                  // 图片加载完成后，更新 imagezongkai 变量
                  this.imagezongkai = imageAdcout;
                  const aDCOutputSwitch = new Konva.Image({
                    x: xSpacing * 4 + dcScreenCabinetWidth + 20,
                    y: yStart + subComponentSpacing+subComponentHeight+35,
                    image: this.imagezongkai, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'aDCOutputSwitch',
                    draggable:true
                  });
                  aGroup.add(aDCOutputSwitch);
                  // 重新绘制 layer 和 stage
                  layer.draw();
                  this.stage.draw();
                };
                imageAdcout.src = require("@/assets/电流互感器.png");
                //子开关之前的开关
                const imageSplitswitch = new Image();
                imageSplitswitch.onload = () => {
                  // 图片加载完成后，更新 imagezongkai 变量
                  this.imagezongkai = imageSplitswitch;
                  const aSplitSwitchImage = new Konva.Image({
                    x: xSpacing * 6 + dcScreenCabinetWidth + 20,
                    y: yStart+ subComponentSpacing+subComponentHeight+30,
                    image: this.imagezongkai, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'aSplitSwitchImage',
                    rotation:-90,
                    scaleX: -1  // 水平翻转
                  });
                  aGroup.add(aSplitSwitchImage);
                  // 重新绘制 layer 和 stage
                  layer.draw();
                  this.stage.draw();
                };
                imageSplitswitch.src = require("@/assets/openswitch.png");
                 // 与 verticalLineA 垂直的线，从 verticalLineA 中点向下延伸 100 像素
                 const verticalLineAMidX = xSpacing / 2 + dcScreenCabinetWidth + dcPowerCabinetWidth * 3;
                const verticalLineAMidY = yStart + dcPowerCabinetHeight - inletWireHeight / 2;
                const perpendicularLineA = createLine(
                  verticalLineAMidX,
                  verticalLineAMidY-this.Alist.branch.length*10,
                  verticalLineAMidX,
                  verticalLineAMidY + this.Alist.branch.length*45,
                  'red',
                  2,
                  'perpendicularLineA'
                );
                aGroup.add(perpendicularLineA);
                //根据数组长度延伸对应条数的线
                if(this.Alist.branch){
                  const branchLength = this.Alist.branch.length;
                  const verticalLineAEndX = xSpacing / 2 + dcScreenCabinetWidth + dcPowerCabinetWidth * 3;
                  const verticalLineAY = yStart + dcPowerCabinetHeight - inletWireHeight / 2-branchLength*5;
                  const lineSpacing = 50; // 引申线之间的间距
                  const halfHeight = (this.stage.height() / 2) - dcPowerCabinetHeight; // 计算每路的高度（除去配电柜高度）
                  const rectY = branchLength*60; // 计算条线占据高度
                  for (let i = 0; i < branchLength; i++) {
                    const newLine = createLine(
                      verticalLineAEndX,
                      verticalLineAY+ i * lineSpacing, 
                      verticalLineAEndX + 300, // 这里设置一个固定的延伸长度，你可以根据需要调整
                      verticalLineAY + i * lineSpacing,
                      'red',
                      2,
                      `rightExtendedLine${i}`
                    );
                    aGroup.add(newLine);
                    let imageSrc;
                    if (this.Alist.branch[i].status == "在线") {
                      imageSrc = require("@/assets/openswitch.png");
                    }else if(this.Alist.branch[i].status == "故障"){
                      imageSrc = require("@/assets/fault.png"); // 假设有关闭状态的图片
                    } else {
                      imageSrc = require("@/assets/closeswitch.png"); // 假设有关闭状态的图片
                    }
                    const image = new Image();
                    image.onload = () => {
                      const lineImage = new Konva.Image({
                        x: verticalLineAEndX + 150, // 图片的 x 坐标，可以根据需要调整
                        y: verticalLineAY + i * lineSpacing - 25, // 图片的 y 坐标，可以根据需要调整
                        image: image,
                        width: subComponentWidth,
                        height: subComponentHeight,
                        name: `lineImage${i}`,
                        rotation:-90,
                        scaleX: -1
                      });
                      aGroup.add(lineImage);
                      layer.draw();
                      this.stage.draw();
                    };
                    image.src = imageSrc;
                     // 创建表格
                    const tableWidth = 200; // 表格宽度
                    const tableHeight = this.Alist.branch.length * 20; // 根据 A 路分支数量动态设置表格高度
                    const tableX = verticalLineAEndX + 300; // 表格的 x 坐标，放置在线的末端
                    const tableY = verticalLineAY-70; // 表格的 y 坐标
                    // / 表格的行数和列数
                    const rows = this.Alist.branch.length+1; // 行数根据 A 路分支数量确定
                    const cols = 2;
                    // 单元格的宽度和高度
                    const cellWidth = tableWidth / cols;
                    const cellHeight = 50; // 固定单元格高度
                    // 创建一个组来管理表格元素
                    const tableGroup = new Konva.Group();
                    // 第一行（表头）
                    for (let col = 0; col < cols; col++) {
                      const cellX = tableX + col * cellWidth;
                      const cellY = tableY;
                      // 创建表头单元格边框（矩形）
                      const cellRect = new Konva.Rect({
                        x: cellX,
                        y: cellY,
                        width: cellWidth,
                        height: cellHeight,
                        stroke: 'black',
                        strokeWidth: 1,
                        name: `tableCellRect_0_${col}`
                      });
                      // 表头的文本内容
                      let cellTextContent = '';
                      if (col === 0) {
                        cellTextContent = '设备编号';
                      } else if (col === 1) {
                        cellTextContent = '设备名称';
                      }
                      // 创建表头单元格中的文本
                      const cellText = new Konva.Text({
                        x: cellX + 5,
                        y: cellY + 5,
                        text: cellTextContent,
                        fontSize: 10,
                        fontFamily: 'Arial',
                        fill: 'black',
                        align: 'center', // 水平居中
                        textAlign: 'center', // 文本内容水平居中
                        verticalAlign: 'middle', // 垂直居中
                        width: cellWidth, // 设置文本宽度与单元格宽度相同
                        height: cellHeight, // 设置文本高度与单元格高度相同
                        name: `tableCellText_0_${col}`
                      });
                      tableGroup.add(cellRect);
                      tableGroup.add(cellText);
                    }
                    // 从第二行开始填充数据
                    this.Alist.branch.forEach((branch, row) => {
                      for (let col = 0; col < cols; col++) {
                        const cellX = tableX + col * cellWidth;
                        const cellY = tableY + (row + 1) * cellHeight; // 注意这里的 row + 1，因为表头占了第一行
                        // 创建单元格边框（矩形）
                        const cellRect = new Konva.Rect({
                          x: cellX,
                          y: cellY,
                          width: cellWidth,
                          height: cellHeight,
                          stroke: 'black',
                          strokeWidth: 1,
                          name: `tableCellRect_${row + 1}_${col}`
                        });
                        // 根据列数填充不同的数据
                        let cellTextContent = '';
                        if (col === 0) {
                          cellTextContent = branch.deviceId;
                        } else if (col === 1) {
                          cellTextContent = branch.deviceName;
                        }
                        // 创建单元格中的文本
                        const cellText = new Konva.Text({
                          x: cellX + 5,
                          y: cellY + 5,
                          text: cellTextContent,
                          fontSize: 10,
                          fontFamily: 'Arial',
                          fill: 'black',
                          align: 'center', // 水平居中
                          textAlign: 'center', // 文本内容水平居中
                          verticalAlign: 'middle', // 垂直居中
                          width: cellWidth, // 设置文本宽度与单元格宽度相同
                          height: cellHeight, // 设置文本高度与单元格高度相同
                          name: `tableCellText_${row + 1}_${col}`
                        });
                        // 在每个单元格右侧新建矩形 显示对应的数据
                        const cellRightRectX = cellX + cellWidth;
                        const cellRightRectWidth = 80; // 右侧矩形的宽度
                        const cellRightRect = new Konva.Rect({
                          x: cellRightRectX,
                          y: cellY,
                          width: cellRightRectWidth,
                          height: cellHeight,
                          strokeWidth: 1,
                          fill: 'lightgray',
                          name: `tableCellRightRect_${row + 1}_${col}`,
                          visible: false // 默认不显示
                        });
                        // 创建一个 Konva.Text 元素用于显示 popupContent
                        const cellRightText = new Konva.Text({
                          x: cellRightRectX + 15, // 稍微偏移一点，避免紧贴矩形边缘
                          y: cellY + 20,
                          text: '', // 初始文本为空
                          fontSize: 12,
                          fontFamily: 'Arial',
                          align: 'left',
                          textAlign: 'left',
                          name: `tableCellRightText_${row + 1}_${col}`,
                          visible: false // 默认不显示
                        });
                        // 添加鼠标移入和移出事件监听器
                        if (col === 1) {
                          cellText.on('mouseenter', () => {
                            this.popupContent = `电压: ${branch.avoltage},电流: ${branch.acurrent}\n功率: ${branch.apower},状态: ${branch.status}`;
                            cellRightText.visible(true); // 显示文本
                            cellRightText.text(this.popupContent); // 更新文本内容
                            layer.draw(); // 重新绘制图层以显示更新后的文本
                          });
                          cellText.on('mouseleave', () => {
                            this.popupContent = '';
                            cellRightText.text(this.popupContent); // 清空文本内容
                            layer.draw(); // 重新绘制图层以显示更新后的文本
                          });
                        }
                        tableGroup.add(cellRect);
                        tableGroup.add(cellText);
                        aGroup.add(cellRightRect);
                        aGroup.add(cellRightText);
                      }
                    });
                    aGroup.add(tableGroup);
                    // 限制矩形框在A路的50%高度内
                    if (rectY > halfHeight) {
                      this.scaleAgroup = halfHeight / rectY;
                      aGroup.scale({ x: 1, y: this.scaleAgroup});
                      cGroup.scale({ x: 1, y: this.scaleAgroup});
                      // break;
                    }
                  }
                }
                // 将 aGroup 添加到 mainGroup 中
                mainGroup.add(aGroup);
                mainGroup.add(cGroup);
                aGroup.moveToTop();
                layer.draw();
                this.stage.draw();
              }
              
              if (this.Blist) {
                // 创建 B 路相关元素的组
                const bGroup = new Konva.Group();
                // 绘制进电线 B 路
                const inletWireCircleB = createCircle(
                  xSpacing / 2,
                  this.stage.height() / 2 + 50 + (dcPowerCabinetHeight - inletWireHeight) / 2,
                  inletWireWidth / 2,
                  'blue',
                  'inletWireCircleB'
                );
                bGroup.add(inletWireCircleB);
                const inletWireB = createArrow(
                  xSpacing / 2,
                  this.stage.height() / 2 + 50 + (dcPowerCabinetHeight - inletWireHeight) / 2 + inletWireWidth / 2,
                  inletWireHeight - inletWireWidth,
                  'blue',
                  'inletWireB'
                );
                bGroup.add(inletWireB);
                // B路与箭头垂直的线
                const verticalLineB = createLine(
                  xSpacing / 2,
                  this.stage.height() / 2 + 50 + dcPowerCabinetHeight - inletWireHeight / 2,
                  xSpacing / 2 + dcScreenCabinetWidth + dcPowerCabinetWidth * 3,
                  this.stage.height() / 2 + 50 + dcPowerCabinetHeight - inletWireHeight / 2,
                  'blue',
                  2,
                  'verticalLineB'
                );
                const dGroup = new Konva.Group();
                dGroup.add(verticalLineB)
                // B路总开关
                const imageBMainswitch = new Image();
                imageBMainswitch.onload = () => {
                  // 图片加载完成后，更新 imagezongkai 变量
                  this.imagezongkai = imageBMainswitch;
                  const bMainSwitchImage = new Konva.Image({
                    x: xSpacing + subComponentSpacing,
                    y: this.stage.height() / 2 + 50 + subComponentSpacing + subComponentHeight + 28,
                    image: this.imagezongkai, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'bMainSwitchImage',
                    rotation: -90,
                    scaleX: -1
                  });
                  bGroup.add(bMainSwitchImage);
                  // 重新绘制 layer 和 stage
                  layer.draw();
                  this.stage.draw();
                };
                imageBMainswitch.src = require("@/assets/switchopen.png"); 
                //B路AC/DC
                const bRectifierModule = createRectAndText(
                  xSpacing + subComponentSpacing*3 + subComponentWidth,
                  this.stage.height() / 2 + 50 + dcPowerCabinetHeight - dcScreenCabinetHeight + subComponentSpacing*2,
                  subComponentWidth,
                  subComponentHeight,
                  'white',
                  'AC',
                  'DC',
                  'bRectifierModule'
                );
                bGroup.add(bRectifierModule);
                // 获取 bRectifierModule 的位置和尺寸信息
                const bRectifierX = bRectifierModule.children[0].x();
                const bRectifierY = bRectifierModule.children[0].y();
                const bRectifierWidth = bRectifierModule.children[0].width();
                const bRectifierHeight = bRectifierModule.children[0].height();
                // 向下引申的线
                const downLine = createLine(
                  bRectifierX + bRectifierWidth / 2, // 从矩形底部中间开始
                  bRectifierY + bRectifierHeight+5,
                  bRectifierX + bRectifierWidth / 2,
                  bRectifierY + bRectifierHeight + 50, // 向下延伸 50 像素
                  'black',
                  2,
                  'downLineFromRect'
                );
                // 右侧引申的线
                const rightLine = createLine(
                  bRectifierX + bRectifierWidth, // 从矩形右侧中间开始
                  bRectifierY + bRectifierHeight / 2,
                  bRectifierX + bRectifierWidth + 50, // 向右延伸 50 像素
                  bRectifierY + bRectifierHeight / 2,
                  'black',
                  2,
                  'rightLineFromRect'
                );
                // 右侧引申线再向下延伸的线
                const rightDownLine = createLine(
                  bRectifierX + bRectifierWidth + 50, // 从右侧引申线的末端开始
                  bRectifierY + bRectifierHeight / 2,
                  bRectifierX + bRectifierWidth + 50,
                  bRectifierY + bRectifierHeight + 50, // 向下延伸到和向下引申线相同的高度
                  'black',
                  2,
                  'rightDownLineFromRect'
                );
                //引申地线
                const connectLine = createLine(
                  bRectifierX + bRectifierWidth / 2,
                  bRectifierY + bRectifierHeight + 50,
                  bRectifierX + bRectifierWidth + 50,
                  bRectifierY + bRectifierHeight + 50,
                  'black',
                  2,
                  'connectLine'
                );
                const lineMidX = (bRectifierX + bRectifierWidth / 2 + bRectifierX + bRectifierWidth + 50) / 2;
                const lineMidY = bRectifierY + bRectifierHeight + 50;
                const imageOnLine  = new Image();
                imageOnLine.onload = () => {
                  const konvaImage = new Konva.Image({
                    x: lineMidX + 15, // 根据图片大小调整位置
                    y: lineMidY - 10, // 根据图片大小调整位置
                    image: imageOnLine,
                    width: 20, // 图片宽度
                    height: 20, // 图片高度
                    name: 'imageOnLine',
                    rotation:90
                  });
                  bGroup.add(konvaImage);
                  layer.draw();
                };
                imageOnLine.src = require("@/assets/switchclose.png");
                bGroup.add(downLine);
                bGroup.add(rightLine);
                bGroup.add(rightDownLine);
                bGroup.add(connectLine);

                // B路汇聚终端
                const imageBterm = new Image();
                imageBterm.onload = () => {
                  this.imageBterm = imageBterm;
                  const bTerminal = new Konva.Image({
                    x: xSpacing * 3 + dcScreenCabinetWidth +15,
                    y: this.stage.height() / 2+ 50 + subComponentSpacing+subComponentHeight+25,
                    image: this.imageBterm, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'bTerminal',
                    rotation:90,
                    draggable:true
                  });
                  bGroup.add(bTerminal);
                  layer.draw();
                  this.stage.draw();
                };
                imageBterm.src = require("@/assets/避雷器.png");
                // B路直流输出总开关
                const imageBdcout = new Image();
                imageBdcout.onload = () => {
                  this.imageBdcout = imageBdcout;
                  const bDCOutputSwitch = new Konva.Image({
                    x: xSpacing * 4 + dcScreenCabinetWidth + 20,
                    y: this.stage.height() / 2 + 50 + subComponentSpacing+subComponentHeight+35,
                    image: this.imageBdcout, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'bDCOutputSwitch',
                    draggable:true
                  });
                  bGroup.add(bDCOutputSwitch);
                  // 重新绘制 layer 和 stage
                  layer.draw();
                  this.stage.draw();
                };
                imageBdcout.src = require("@/assets/电流互感器.png"); 
                //子开关之前的开关
                const imageSplitswitch = new Image();
                imageSplitswitch.onload = () => {
                  // 图片加载完成后，更新 imagezongkai 变量
                  this.imagezongkai = imageSplitswitch;
                  const aSplitSwitchImage = new Konva.Image({
                    x: xSpacing * 6 + dcScreenCabinetWidth + 20,
                    y: this.stage.height() / 2 + 50+ subComponentSpacing+subComponentHeight+30,
                    image: this.imagezongkai, // 使用加载完成的图片对象
                    width: subComponentWidth,
                    height: subComponentHeight,
                    name: 'aSplitSwitchImage',
                    rotation:-90,
                    scaleX: -1  // 水平翻转
                  });
                  bGroup.add(aSplitSwitchImage);
                  // 重新绘制 layer 和 stage
                  layer.draw();
                  this.stage.draw();
                };
                imageSplitswitch.src = require("@/assets/openswitch.png");  
               // 与 verticalLineB 垂直的线，从 verticalLineB 中点向下延伸 100 像素 
               const verticalLineAMidX = xSpacing / 2 + dcScreenCabinetWidth + dcPowerCabinetWidth * 3;
                const verticalLineAMidY = this.stage.height() / 2 + 50 + dcPowerCabinetHeight - inletWireHeight / 2;
                const perpendicularLineB = createLine(
                  verticalLineAMidX,
                  verticalLineAMidY-this.Blist.branch.length*10,
                  verticalLineAMidX,
                  verticalLineAMidY + this.Blist.branch.length*45,
                  'blue',
                  2,
                  'perpendicularLineB'
                );
                bGroup.add(perpendicularLineB);   
                //根据数组长度延伸对应条数的线
                if(this.Blist.branch){
                  const branchLength = this.Blist.branch.length;
                  const verticalLineAEndX = xSpacing / 2 + dcScreenCabinetWidth + dcPowerCabinetWidth * 3;
                  const verticalLineAY = this.stage.height() / 2 + 50 + dcPowerCabinetHeight - inletWireHeight / 2-branchLength*5;
                  const lineSpacing = 50; // 引申线之间的间距
                  const halfHeight = (this.stage.height() / 2) + dcPowerCabinetHeight; // 计算每路的高度（除去配电柜高度）
                  const rectY = branchLength*60; // 计算条线占据高度
                  let totalScaleY = 1; // 用于记录总的缩放比例
                  for (let i = 0; i < branchLength; i++) {
                    const newLine = createLine(
                      verticalLineAEndX,
                      verticalLineAY+ i * lineSpacing, 
                      verticalLineAEndX + 300, // 这里设置一个固定的延伸长度，你可以根据需要调整
                      verticalLineAY + i * lineSpacing,
                      'blue',
                      2,
                      `rightExtendedLine${i}`
                    );
                    bGroup.add(newLine);
                    let imageSrc;
                    if (this.Blist.branch[i].status == "在线") {
                      imageSrc = require("@/assets/openswitch.png");
                    }else if(this.Blist.branch[i].status == "故障"){
                      imageSrc = require("@/assets/fault.png"); // 假设有关闭状态的图片
                    } else {
                      imageSrc = require("@/assets/closeswitch.png"); // 假设有关闭状态的图片
                    }
                    const image = new Image();
                    image.onload = () => {
                      const lineImage = new Konva.Image({
                        x: verticalLineAEndX + 150, // 图片的 x 坐标，可以根据需要调整
                        y: verticalLineAY + i * lineSpacing - 25, // 图片的 y 坐标，可以根据需要调整
                        image: image,
                        width: subComponentWidth,
                        height: subComponentHeight,
                        name: `lineImage${i}`,
                        rotation:-90,
                        scaleX: -1
                      });
                      bGroup.add(lineImage);
                      layer.draw();
                      this.stage.draw();
                    };
                    image.src = imageSrc;
                     // 创建表格
                    const tableWidth = 200; // 表格宽度
                    const tableHeight = this.Blist.branch.length * 20; // 根据 A 路分支数量动态设置表格高度
                    const tableX = verticalLineAEndX + 300; // 表格的 x 坐标，放置在线的末端
                    const tableY = verticalLineAY-70; // 表格的 y 坐标
                    // / 表格的行数和列数
                    const rows = this.Blist.branch.length+1; // 行数根据 A 路分支数量确定
                    const cols = 2;
                    // 单元格的宽度和高度
                    const cellWidth = tableWidth / cols;
                    const cellHeight = 50; // 固定单元格高度
                    // 创建一个组来管理表格元素
                    const tableGroup = new Konva.Group();
                    // 第一行（表头）
                    for (let col = 0; col < cols; col++) {
                      const cellX = tableX + col * cellWidth;
                      const cellY = tableY;
                      // 创建表头单元格边框（矩形）
                      const cellRect = new Konva.Rect({
                        x: cellX,
                        y: cellY,
                        width: cellWidth,
                        height: cellHeight,
                        stroke: 'black',
                        strokeWidth: 1,
                        name: `tableCellRect_0_${col}`
                      });
                      // 表头的文本内容
                      let cellTextContent = '';
                      if (col === 0) {
                        cellTextContent = '设备编号';
                      } else if (col === 1) {
                        cellTextContent = '设备名称';
                      }
                      // 创建表头单元格中的文本
                      const cellText = new Konva.Text({
                        x: cellX + 5,
                        y: cellY + 5,
                        text: cellTextContent,
                        fontSize: 10,
                        fontFamily: 'Arial',
                        fill: 'black',
                        align: 'center', // 水平居中
                        textAlign: 'center', // 文本内容水平居中
                        verticalAlign: 'middle', // 垂直居中
                        width: cellWidth, // 设置文本宽度与单元格宽度相同
                        height: cellHeight, // 设置文本高度与单元格高度相同
                        name: `tableCellText_0_${col}`
                      });
                      tableGroup.add(cellRect);
                      tableGroup.add(cellText);
                    }
                    // 从第二行开始填充数据
                    this.Blist.branch.forEach((branch, row) => {
                      for (let col = 0; col < cols; col++) {
                        const cellX = tableX + col * cellWidth;
                        const cellY = tableY + (row + 1) * cellHeight; // 注意这里的 row + 1，因为表头占了第一行
                        // 创建单元格边框（矩形）
                        const cellRect = new Konva.Rect({
                          x: cellX,
                          y: cellY,
                          width: cellWidth,
                          height: cellHeight,
                          stroke: 'black',
                          strokeWidth: 1,
                          name: `tableCellRect_${row + 1}_${col}`
                        });
                        // 根据列数填充不同的数据
                        let cellTextContent = '';
                        if (col === 0) {
                          cellTextContent = branch.deviceId;
                        } else if (col === 1) {
                          cellTextContent = branch.deviceName;
                        }
                        // 创建单元格中的文本
                        const cellText = new Konva.Text({
                          x: cellX + 5,
                          y: cellY + 5,
                          text: cellTextContent,
                          fontSize: 10,
                          fontFamily: 'Arial',
                          fill: 'black',
                          align: 'center', // 水平居中
                          textAlign: 'center', // 文本内容水平居中
                          verticalAlign: 'middle', // 垂直居中
                          width: cellWidth, // 设置文本宽度与单元格宽度相同
                          height: cellHeight, // 设置文本高度与单元格高度相同
                          name: `tableCellText_${row + 1}_${col}`
                        });
                        // 在每个单元格右侧新建矩形 显示对应的数据
                        const cellRightRectX = cellX + cellWidth;
                        const cellRightRectWidth = 80; // 右侧矩形的宽度
                        const cellRightRect = new Konva.Rect({
                          x: cellRightRectX,
                          y: cellY,
                          width: cellRightRectWidth,
                          height: cellHeight,
                          strokeWidth: 1,
                          fill: 'lightgray',
                          name: `tableCellRightRect_${row + 1}_${col}`,
                          visible: false // 默认不显示
                        });
                        // 创建一个 Konva.Text 元素用于显示 popupContent
                        const cellRightText = new Konva.Text({
                          x: cellRightRectX + 15, // 稍微偏移一点，避免紧贴矩形边缘
                          y: cellY + 20,
                          text: '', // 初始文本为空
                          fontSize: 12,
                          fontFamily: 'Arial',
                          align: 'left',
                          textAlign: 'left',
                          name: `tableCellRightText_${row + 1}_${col}`,
                          visible: false // 默认不显示
                        });
                        // 添加鼠标移入和移出事件监听器
                        if (col === 1) {
                          cellText.on('mouseenter', () => {
                            this.popupContentB = `电压: ${branch.avoltage},电流: ${branch.acurrent}\n功率: ${branch.apower},状态: ${branch.status}`;
                            cellRightText.visible(true); // 显示文本
                            cellRightText.text(this.popupContentB); // 更新文本内容
                            layer.draw(); // 重新绘制图层以显示更新后的文本
                          });
                          cellText.on('mouseleave', () => {
                            this.popupContentB = '';
                            cellRightText.text(this.popupContentB); // 清空文本内容
                            layer.draw(); // 重新绘制图层以显示更新后的文本
                          });
                        }
                        tableGroup.add(cellRect);
                        tableGroup.add(cellText);
                        bGroup.add(cellRightRect);
                        bGroup.add(cellRightText);
                      }
                    });
                    bGroup.add(tableGroup);
                    // 限制矩形框在B路的50%高度内
                    // if (rectY > halfHeight) {
                    //   const scaleBgroup = halfHeight / rectY;
                    //   bGroup.scale({ x: 1, y: scaleBgroup});
                    //   dGroup.scale({ x: 1, y: scaleBgroup});
                    //   // break;
                    // } 

                    if (rectY > halfHeight) {
                      console.log(111111)
                      const scaleBgroup = halfHeight / rectY;
                      totalScaleY *= scaleBgroup; // 累积缩放比例
                      // 调整 bGroup 和 dGroup 的位置和缩放
                      const newY = halfHeight - rectY * totalScaleY;
                      // 确保 newY 不会导致元素移出可视区域
                      const minY = 0; // 最小 y 坐标
                      const finalY = Math.max(minY, newY);
                      bGroup.y(finalY); // 调整 y 坐标以防止往上跑
                      bGroup.scale({ x: 1, y: totalScaleY });
                      // 对 dGroup 也进行同样的处理
                      dGroup.y(finalY);
                      dGroup.scale({ x: 1, y: totalScaleY });
                      // 确保缩放比例不会过小
                      const minScale = 0.1; // 最小缩放比例
                      if (totalScaleY <= this.scaleAgroup) {
                        totalScaleY = this.scaleAgroup;
                        bGroup.scale({ x: 1, y: totalScaleY });
                        dGroup.scale({ x: 1, y: totalScaleY });
                      }
                    }else{
                      console.log(222222)
                      const scaleBgroup = halfHeight / rectY;
                      totalScaleY *= scaleBgroup; // 累积缩放比例
                      // 调整 bGroup 和 dGroup 的位置和缩放
                      const newY = halfHeight - rectY * totalScaleY;
                      // 确保 newY 不会导致元素移出可视区域
                      const minY = 0; // 最小 y 坐标
                      const finalY = Math.max(minY, newY);
                      bGroup.y(finalY); // 调整 y 坐标以防止往上跑
                      bGroup.scale({ x: 1, y: totalScaleY });
                      // 对 dGroup 也进行同样的处理
                      dGroup.y(finalY);
                      dGroup.scale({ x: 1, y: totalScaleY });
                      // 确保缩放比例不会过小
                      const minScale = 0.1; // 最小缩放比例
                      if (totalScaleY > this.scaleAgroup) {
                        if(this.scaleAgroup==0){
                          totalScaleY = 1;
                        }else{
                          totalScaleY = this.scaleAgroup;
                        }
                        bGroup.scale({ x: 1, y: totalScaleY });
                        dGroup.scale({ x: 1, y: totalScaleY });
                      }
                      
                    }
                  }
                }                
                // 将 bGroup 添加到 mainGroup 中
                mainGroup.add(bGroup);
                mainGroup.add(dGroup);
                bGroup.moveToTop();
                layer.draw();
                this.stage.draw();
              }
              layer.add(mainGroup);
            this.stage.add(layer);
          layer.draw();
          this.stage.draw();
          // 鼠标按下事件
          this.stage.on('mousedown touchstart', (e) => {
            this.isDragging = true;
            this.lastPointerPos = this.stage.getPointerPosition();
          });

          // 鼠标移动事件
          this.stage.on('mousemove touchmove', (e) => {
            if (!this.isDragging) return;
            const pos = this.stage.getPointerPosition();
            const dx = pos.x - this.lastPointerPos.x;
            const dy = pos.y - this.lastPointerPos.y;
            this.stage.position({
              x: this.stage.position().x + dx,
              y: this.stage.position().y + dy
            });
            this.lastPointerPos = pos;
            this.stage.batchDraw();
          });
          // 鼠标抬起事件
          this.stage.on('mouseup touchend', () => {
            this.isDragging = false;
          });
          this.stage.on('wheel', (evt) => {
              const oldScale = this.stage.scaleX();
              const pointer = this.stage.getPointerPosition();
              const scaleBy = 1.1; // 缩放比例，1.1 表示每次缩放增加10%
              const mousePointTo = {
                x: (pointer.x - this.stage.x()) / oldScale,
                y: (pointer.y - this.stage.y()) / oldScale,
              }; // 将鼠标指针相对于画布的位置转换为相对于缩放后的画布位置
              const newScale = evt.evt.deltaY < 0 ? oldScale * scaleBy : oldScale / scaleBy; // 根据滚轮方向决定是放大还是缩小
              this.stage.scale({ x: newScale, y: newScale }); // 应用新的缩放比例
              this.stage.position({ // 保持鼠标指针在缩放后的位置上不变
                x: pointer.x - mousePointTo.x * newScale,
                y: pointer.y - mousePointTo.y * newScale,
              });
              this.stage.batchDraw(); // 刷新舞台以显示新的缩放状态
            });
          })
        // }).catch(() => {
        //   // this.loading = false;
        // });
      }
    }
  }
</script>
<style lang="scss" scoped>
.top{
  width: 100%;
    height: 63px;
   display: flex;
    font-size: 14px;
    justify-content: space-between;
      .top_left{
          width: 300px;
          height: 63px;
          line-height: 63px;
          .textA{
            font-weight: 400;
            color: #7E7E7E;
            margin-right: 5px;
          }
          .textB{
            font-weight: 400;
            color: #3579F6;
            margin-left: 5px;
          }
        }
      .top_right{
          width: 200px;
          height: 63px;
          display: flex;
          font-size: 20px;
          .box_A{
            width: 54px;
            height: 32px;
            margin: 15px 10px 0 0;
            line-height: 32px;
            text-align: center;
            background: #67CD78;
            border-radius: 2px;
          }
          .box_B{
            width: 54px;
            height: 32px;
            line-height: 32px;
            text-align: center;
            margin-top: 15px;
            background: #1B6BFF;
            border-radius: 2px;
            margin-top: 15px;
          }
    }
}
#scroll-container {
  /* 设置为可滚动 */
  overflow: auto;
  width: 100% !important;
  height: 1080px !important;
  // background-color: #7E7E7E;
}
.bottom{
  width: 100% !important;
  height: 1000px !important; 
  // background-color: aquamarine; 
}
</style>